package com.ziyucoding.springboot.labs.lab10.seatdemo.atscfeign.orderservice.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.ziyucoding.springboot.labs.lab10.seatdemo.atscfeign.orderservice.OrderDO;
import com.ziyucoding.springboot.labs.lab10.seatdemo.atscfeign.orderservice.dao.OrderDao;
import com.ziyucoding.springboot.labs.lab10.seatdemo.atscfeign.orderservice.feign.AccountServiceFeignClient;
import com.ziyucoding.springboot.labs.lab10.seatdemo.atscfeign.orderservice.feign.ProductServiceFeignClient;
import com.ziyucoding.springboot.labs.lab10.seatdemo.atscfeign.orderservice.feign.dto.AccountReduceBalanceDTO;
import com.ziyucoding.springboot.labs.lab10.seatdemo.atscfeign.orderservice.feign.dto.ProductReduceStockDTO;
import com.ziyucoding.springboot.labs.lab10.seatdemo.atscfeign.orderservice.service.OrderService;
import io.seata.core.context.RootContext;
import io.seata.integration.http.DefaultHttpExecutor;
import io.seata.spring.annotation.GlobalTransactional;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.util.Map;


/**
 * 订单 service实现类
 *
 * @author ziyucoding
 * @date 2022-11-03
 **/
@Service
public class OrderServiceImpl implements OrderService {
    private Logger logger = LoggerFactory.getLogger(getClass());

    @Autowired
    private OrderDao orderDao;

    @Autowired
    private ProductServiceFeignClient productService;

    @Autowired
    private AccountServiceFeignClient accountService;

    @Override
    @GlobalTransactional // 声明全局事务
    public Integer createOrder(Long userId, Long productId, Integer price) throws Exception {
        // 购买数量，暂时设置为 1。
        Integer amount = 1;

        logger.info("[createOrder] 当前 XID: {}", RootContext.getXID());

        // 扣减库存
        this.reduceStock(productId, amount);

        // 扣减余额
        this.reduceBalance(userId, price);

        // 保存订单
        OrderDO order = new OrderDO();
        order.setUserId(userId);
        order.setProductId(productId);
        order.setPayAmount(amount * price);
        orderDao.saveOrder(order);
        logger.info("[createOrder] 保存订单: {}", order.getId());

        // 返回订单编号
        return order.getId();
    }

    /**
     * 扣除库存
     *
     * @param productId
     * @param amount
     * @return void
     **/
    private void reduceStock(Long productId, Integer amount) throws IOException {
        ProductReduceStockDTO productReduceStockDTO = new ProductReduceStockDTO();
        productReduceStockDTO.setProductId(productId);
        productReduceStockDTO.setAmount(amount);
        Map<String, Object> productResult = productService.reduceStock(productReduceStockDTO);
        Boolean isSuccess = Boolean.valueOf(String.valueOf(productResult.get("data")));
        if (!isSuccess) {
            throw new RuntimeException("扣除库存失败");
        }
    }

    /**
     * 扣除余额
     *
     * @param userId
     * @param price
     * @return void
     **/
    private void reduceBalance(Long userId, Integer price) throws IOException {
        AccountReduceBalanceDTO accountReduceBalanceDTO = new AccountReduceBalanceDTO();
        accountReduceBalanceDTO.setUserId(userId);
        accountReduceBalanceDTO.setPrice(price);
        Map<String, Object> accountResult = accountService.reduceBalance(accountReduceBalanceDTO);
        Boolean isSuccess = Boolean.valueOf(String.valueOf(accountResult.get("data")));
        if (!isSuccess) {
            throw new RuntimeException("扣除余额失败");
        }
    }


}
